<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" errorPage="/error.jsp"%>
<%@page import="dbexp.model.Index"%>
<%@page import="dbexp.model.Column"%>
<%@page import="dbexp.model.db.DbUser"%>
<%@page import="dbexp.connection.DbMetaData"%>
<%@page import="org.json.JSONArray"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%
DbUser u = (DbUser)session.getAttribute("USER");
String name = request.getParameter("name");
String schema = request.getParameter("schema");
String tablespace = "USERS";
boolean nowy = (name==null || name.trim().equals("null")) && (schema==null || schema.trim().equals("null"));
String id = schema+"-"+name;
Index obj = null;
String save = "Zapisz";
String columns_data = "";
String onTable = "";
String onSchema = "";
boolean bitmap = false;
boolean reverse = false;
boolean unique = false;
if(nowy){
	name = "Nowy indeks";
	schema=u.getSchemaName();
	save = "Utwórz";
}else{
	obj = DbMetaData.getIndex(u, name.toUpperCase(), schema.toUpperCase());
	name = obj.getName();
	schema = obj.getSchema();
	tablespace = obj.getTablespace();
	bitmap=obj.isBitmap();
	reverse=obj.isReverse();
	unique=obj.isUnique();
	onTable=obj.onTable();
	onSchema=obj.onSchema();
	List<Column> columns = obj.getColumns();
	JSONArray data = new JSONArray();
	for (Iterator<Column> iterator = columns.iterator(); iterator.hasNext();) {
		Column column = (Column) iterator.next();
		List<String> properties = new ArrayList<String>();
		properties.add(column.getName().toLowerCase());
		properties.add(column.getDataType());
		data.put(properties);
	}
	columns_data = data.toString();
}
//{header: "Email", width: 100, sortable: true, dataIndex: 'email', editor: textField},

%>
<div class="container" style="width:500px">
    <div id="<%=id%>-form"></div>
    <div id="<%=id%>-grid"></div>
</div>
<script language="JavaScript">
//try{
var reader = new Ext.data.JsonReader({
    totalProperty: 'total',
    successProperty: 'success',
    idProperty: 'name',
    root: 'data'
},[
   {name:"name"},
   {name:"dataType"}
   ]);

var store = new Ext.data.Store({
	baseParams: {name:'<%=name %>', schema:'<%=schema %>',tablespace:'<%=tablespace%>'},
    id: 'name',
    proxy: new Ext.data.HttpProxy({
        url:'db/table/column/read.jsp',method:'POST'
    }),
    reader: reader
});
<%if(!nowy){%>
var store = new Ext.data.SimpleStore({
	id:'name',
	fields:[{name:'name'},{name:'dataType'}],
	data:<%=columns_data%>
});
<%}%>
var toStore = new Ext.data.SimpleStore({
	id:'name',
	fields:[{name:'name'}],
	data:[[]]
});
<%if(nowy){%>
columnSelector = new Ext.ux.ItemSelector( {
	name :"columns",
	fieldLabel :"Kolumny",
	dataFields : [ "name" ],
	msWidth :250,
	msHeight :200,
	valueField :"name",
	displayField :"name",
	imagePath: 'images/',
	toLegend :"Wybrane",
	toStore : toStore,
	fromLegend :"Dostępne",
	fromStore :store
});

var schemaCmb = combo({
	id: 'schema',
	name:'onSchema',
	valueField: 'name',
	displayField: 'name',
	triggerAction: 'all',
	value:'<%=schema%>',
	fieldLabel: 'Schemat',
	anchor:'100%'
});
var tableCmb = combo({
	store: new Ext.data.JsonStore({  
         url:'db/obj.jsp',  
         root:'data',  
         fields: ['name','name'],
         baseParams : {
         	owner:'<%=schema%>',
            t: 32
        }
     }),
	id: 'name',
	name:'onTable',
	valueField: 'name',
	displayField: 'name',
	triggerAction: 'all',
	emptyText: '',
	fieldLabel: 'Tabela',
	anchor:'100%'
});
schemaCmb.on('select', function(cmb, record, index){ //krok 1  
	tableCmb.clearValue(); //krok 2
	tableCmb.getStore().reload({ //krok 3  
        params: {
        	owner: record.get('name'),	//krok 4
            t: 32 //krok 5
        }
    });
}, this);

tableCmb.on('select', function(cmb, record, index){ //krok 1  
	toStore.removeAll(); //krok 2  
    store.reload({ //krok 3  
        params: {
        	schema: schemaCmb.getRawValue(), //krok 4
        	name: record.get('name'),
            t: 32 //krok 5
        }
    });
}, this);
<%}%>
var tableColumns = new Ext.grid.ColumnModel( [
    {header: "Nazwa", width: 90, dataIndex: 'name'},
    {header: "Typ", width: 80, dataIndex: 'dataType'}
]);
tableColumns.defaultSortable = true;
//store.load();

TableColumnsGrid = Ext.extend(Ext.grid.GridPanel, {
    <%if(!nowy){%>renderTo: '<%=id%>-grid',<%}%>
    iconCls: 'silk-grid',
    frame: true,
    border:false,
    title: 'Kolumny',
    height: 300,anchor:'100%',
    //width: 890,
    style: 'margin-top: 10px',

    initComponent : function() {
        this.viewConfig = {
            forceFit: false
        };
        TableColumnsGrid.superclass.initComponent.call(this);
    },
   	onSuccess:function(action) {
   		obj = Ext.util.JSON.decode(action.response.responseText);
        var root = Ext.getCmp('api-tree').getRootNode();
        catNode={};
    	if( (catNode=root.findChild("t","32"))!=null){
    		catNode.reload();
    	}
    },
    onFailure:function(action) {
    		this.showError(action.response.responseText);
    },
    showError:function(msg) {
    	obj = Ext.util.JSON.decode(msg);
    	 title = obj.error.title||'Error';
    	 Ext.Msg.show({
    		title:title,
    	 	msg:obj.error.msg||obj.error,
    	 	modal:true,
    	 	icon:Ext.Msg.ERROR,
    	 	buttons:Ext.Msg.OK
    	 });
    }
});
var tableGrid = new TableColumnsGrid({
	<%if(!nowy){%>renderTo: '<%=id%>-grid',<%}%>
    store: store,
    defaults: {
        sortable: true           
    },
    cm : tableColumns
});

TableForm = Ext.extend(Ext.form.FormPanel, {
    renderTo: '<%=id%>-form',
    id:'<%=id%>-table-form',
    frame: true,
    width: 900,
    url:'db/index.jsp',
    defaultType: 'textfield',
    defaults: {
        anchor: '100%'
    },
    initComponent : function() {
    	 var config={
    	 	defaults: {
    	    	anchor: '100%'
    	    },
    	    defaultType: 'textfield',
    		monitorValid:true,
       		items: [
				{fieldLabel: 'Nazwa', name: 'name', allowBlank: false,value:'<%=name %>'<%=(nowy)?"":",readOnly:true,disabled:true"%>},
       			<%=(nowy)?"combo({emptyText:'"+schema+"',anchor:'100%'})":"{fieldLabel:'Schemat',name:'schema',allowBlank:false,value:'"+schema+"',readOnly:true,disabled:true}"%>,
       			<%=(nowy)?"comboTS({emptyText:'"+tablespace+"',anchor:'100%'})":"{fieldLabel:'Przestrzeń tabel',name:'tablespace',allowBlank:false,value:'"+tablespace+"',readOnly:true,disabled:true}"%>,
       			{
           			xtype:'fieldset',
           			title:'Index na tabeli',
           			anchor:'100%',
           			width:800,
           			layout:'form',
           			defaultType: 'textfield',
           			items:[
           			<%=(nowy)?"schemaCmb":"{fieldLabel:'Schemat',name:'onSchema',allowBlank:false,value:'"+onSchema+"',readOnly:true,disabled:true,anchor:'100%'}"%>,
           			<%=(nowy)?"tableCmb":"{fieldLabel:'Tabela',name:'onTable',allowBlank:false,value:'"+onTable+"',readOnly:true,disabled:true,anchor:'100%'}"%>,
                   	<%if(nowy){%>
                   	{		
                       	xtype:'fieldset',
						title:'Kolumny',		
						layout:'fit',		
						height:350,		
						border:false,		
						autoScroll:true,
						frame:true,
						bodyStyle:'padding:10px',		
						items:[				
							columnSelector		
						]	
					}
                   	<%}else{%>
       	       	 	tableGrid
       	       	 	<%}%>
       	       	 	]
       			},
       	 		{
					xtype:'fieldset',
					anchor:'99%',
					title:'Opcje',
           	 		items:{
			            xtype: 'checkboxgroup',
			            defaultType:'checkbox',
			            fieldLabel:'',
			            columns:'3',
			            anchor:'45%',
			            <%=((!nowy)?"disabled:true,":"")%>
			            items: [
			                {fieldLabel:'',boxLabel: 'Unikatowy', name: 'unique',checked:<%=unique%>},
			                {fieldLabel:'',boxLabel: 'Bitmap', name: 'bitmap',checked:<%=bitmap%>},
			                {fieldLabel:'',boxLabel: 'Odwrotny', name: 'reverse',checked:<%=reverse%>}
			            ]
		            }
		            
		        }
        	],
        	buttons:[
        	              <%if(nowy){%>{
        	         	    	text: 'Zapisz',
        	         	    	iconCls: 'icon-save',
        	         	    	formBind:true,
        	         	    	scope: this,
        	         	    	handler:this.submit
        	             	}<%}%>
        	             	]
    	};
		Ext.apply(this, Ext.apply(this.initialConfig, config));
		TableForm.superclass.initComponent.apply(this, arguments);
    },
	onRender:function() {
    	TableForm.superclass.onRender.apply(this, arguments);
	    this.getForm().waitMsgTarget = this.getEl();
    },
	onLoadClick:function() {
    	this.load({
	    	url:this.url
	    	,waitMsg:'Ładowanie...'
	    	 ,params:{name:'${name}',schema:'${schema}',action:'get'},method:'POST'
    	});
    },
    submit:function() {
    	this.getForm().submit({
    		url:this.url,
    		scope:this,
    		success:this.onSuccess,
    		failure:this.onFailure,
    		params:{action:'create'},
    		waitTitle:'proszę czekać.....',
    		waitMsg:'Trwa zapisywanie danych...'
    	});
   	},
   	onSuccess:function(form, action) {
   		obj = Ext.util.JSON.decode(action.response.responseText);
        var root = Ext.getCmp('api-tree').getRootNode();
        var category_node = root.findChild("t","1541");
        if(category_node){category_node.reload();}
   		<%if(nowy){%>
    	Ext.Msg.alert('DbExplorer','Z powodzeniem utworzono nowy indeks');
		var w = Ext.getCmp('create-window');
		if(w){
			w.close();
		}
<%}%>
    },
    onFailure:function(form, action) {
    		this.showError(action.response.responseText);
    },
    showError:function(msg) {
    	obj = Ext.util.JSON.decode(msg);
    	 title = obj.error.title||'Error';
    	 Ext.Msg.show({
    		title:title,
    	 	msg:obj.error.msg||obj.error,
    	 	modal:true,
    	 	icon:Ext.Msg.ERROR,
    	 	buttons:Ext.Msg.OK
    	 });
    }
});

Ext.onReady(function() {
    Ext.form.Field.prototype.msgTarget = 'side';
    var indexForm = new TableForm({
        renderTo: '<%=id%>-form'
    });

});
//}catch(e){alert(e);}
</script>